package com.mairuide.datalog;

import com.mairuide._frame.base.BaseRepository;
import com.mairuide._frame.base.BaseServiceProxy;
import com.mairuide._frame.utils.StringUtils;
import com.mairuide.platmanager.PlatManager;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;

@Service
@Transactional
public class DataOperationLogService extends BaseServiceProxy<DataOperationLog> {

	@Resource
	private DataOperationLogRepository dataOperationLogRepository;
	
	@Resource
	private DataOperationDetailLogService dataOperationDetailLogService;
	
	@Resource
	private DataOperationImportLogService dataOperationImportLogService;

	@Override
	protected BaseRepository<DataOperationLog> getBaseRepository() {
		return dataOperationLogRepository;
	}


	/**
	 * 分页查询日志附表信息
	 * @param paramsDataLog
	 * @param pageable
	 * @return
	 */
	@Transactional(readOnly=true)
	public Page<DataOperationLog> findDataOperationLoglList(DataOperationLogParams paramsDataLog, Pageable pageable) {
		
		return dataOperationLogRepository.findAll(new Specification<DataOperationLog>() {
			@Override
			public Predicate toPredicate(Root<DataOperationLog> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicates = new ArrayList<Predicate>();
				if (paramsDataLog.getBeanId() != null) {
					predicates.add(cb.equal(root.get("beanId"), paramsDataLog.getBeanId()));
				}
				/* 创建人查询条件 */
				if (StringUtils.isNotEmpty(paramsDataLog.getCreateUserName())) {
					predicates.add(cb.equal(root.get("createUserName"), paramsDataLog.getCreateUserName()));
				}
				/* 创建时间查询条件 */
				if (StringUtils.isNotEmpty(paramsDataLog.getBeginCreateTimeStr())) {
					 //大于或等于开始时间
                   predicates.add(cb.greaterThanOrEqualTo(root.get("createTime").as(String.class),  paramsDataLog.getBeginCreateTimeStr())); 
				}
				if (StringUtils.isNotEmpty(paramsDataLog.getEndCreateTimeStr())) {
					 //小于或等于结束时间
                  predicates.add(cb.lessThanOrEqualTo(root.get("createTime").as(String.class),  paramsDataLog.getEndCreateTimeStr()+" 23:59:59")); 
				}
				if (paramsDataLog.getShowType()==0){//导入展示
					/* 模块标识查询条件 */
					if (null != paramsDataLog.getModuleFlag() && -1 != paramsDataLog.getModuleFlag() ) {
						predicates.add(cb.equal(root.get("moduleFlag"), paramsDataLog.getModuleFlag()));
					}else {
						Predicate or = cb.or(cb.equal(root.get("moduleFlag"), ModuleFlag.BILLINPUT),cb.equal(root.get("moduleFlag"), ModuleFlag.PHONERECORDINPUT));
						predicates.add(or);
					}
				}else {//其他类型展示
					/* 模块标识查询条件 */
					if (null != paramsDataLog.getModuleFlag() && -1 != paramsDataLog.getModuleFlag() ) {
						predicates.add(cb.equal(root.get("moduleFlag"), paramsDataLog.getModuleFlag()));
					}else {
						predicates.add(cb.notEqual(root.get("moduleFlag"), ModuleFlag.BILLINPUT));
						predicates.add(cb.notEqual(root.get("moduleFlag"), ModuleFlag.PHONERECORDINPUT));
					}
				}
				/* 系统标识查询条件 */
				if (paramsDataLog.getSystemFlag() != null) {
					predicates.add(cb.equal(root.get("systemFlag"), paramsDataLog.getSystemFlag()));
				}

				/* 操作类型查询条件 */
				if (null != paramsDataLog.getActionType() && -1 != paramsDataLog.getActionType()) {
					predicates.add(cb.equal(root.get("actionType"), paramsDataLog.getActionType()));
				}
				
				return cb.and(predicates.toArray(new Predicate[predicates.size()]));
			}
		}, pageable);
	}
	
	/**
	 * 保存操作日志，及子表日志
	 * @param beanId 
	 * @param loginUser 操作人
	 * @param object 操作对象
	 * @param copyObject 操作对象
	 * @param systemFlag 系统标识
	 * @param moduleFlag 模块标识
	 * @param actionType 操作类型
	 * @throws Exception
	 */
	public void save(String beanId, PlatManager loginUser, Object object, Object copyObject
			, SystemFlag systemFlag, ModuleFlag moduleFlag, ActionType actionType) throws Exception {
		
		/* 封装修改字段bean并保存 */
		List<DataOperationDetailLog> dodls = ParseAnnotation.renderingChannelLog(object, copyObject);
		/* 保存主表 */
		DataOperationLog dol = new DataOperationLog();
		dol.setBeanId(beanId);
		dol.setActionType(actionType);
		dol.setCreateTime(new Date());
		dol.setCreateUserId(loginUser.getId());
		dol.setCreateUserName(loginUser.getNickName());
		dol.setModuleFlag(moduleFlag);
		dol.setSystemFlag(systemFlag);
		dataOperationLogRepository.save(dol);
		if (null != dodls && !dodls.isEmpty()) {
			/* 保存子表 */
			for(DataOperationDetailLog dodl : dodls) {
				dodl.setParentLogId(dol.getLogId());
				dataOperationDetailLogService.save(dodl);
			}
		}
	}

	/**
	 * 保存导入日志
	 * @param fileQuantity
	 * @param doils
	 * @param loginUser
	 * @param systemFlag
	 * @param moduleFlag
	 * @param actionType
	 * @throws Exception
	 */
	public Map<String, Object> save(Integer fileQuantity, List<DataOperationImportLog> doils , PlatManager loginUser,
					SystemFlag systemFlag, ModuleFlag moduleFlag, ActionType actionType, String caseManagerId) throws Exception {
		LinkedHashMap<String, Object> linkedHashMap = new LinkedHashMap<>();
		/* 保存主表 */
		DataOperationLog dol = new DataOperationLog();
		dol.setFileQuantity(fileQuantity);
		dol.setActionType(actionType);
		dol.setCreateTime(new Date());
		dol.setCreateUserId(loginUser.getId());
		dol.setCreateUserName(loginUser.getNickName());
		dol.setModuleFlag(moduleFlag);
		dol.setSystemFlag(systemFlag);
		dataOperationLogRepository.save(dol);
		if (null != doils && !doils.isEmpty()) {
			/* 保存子表 */
			String ids="";
			for(DataOperationImportLog dodl : doils) {
				dodl.setParentLogId(dol.getLogId());
				dodl.setCaseManagerId(caseManagerId);
				DataOperationImportLog save = dataOperationImportLogService.save(dodl);
				ids+=save.getImportDetailId()+",";
			}
			if (org.apache.commons.lang3.StringUtils.endsWith(ids,",")){
				ids=ids.substring(0,ids.length()-1);
			}
			linkedHashMap.put("ids",ids);
		}
		return linkedHashMap;
	}
}
